package com.kly.msg.strategy.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.amazonaws.services.s3.Headers;
import com.fqgj.common.utils.MD5;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Maps;
import com.kly.dto.MsgResultDto;
import com.kly.dto.SmsBackRequestDTO;
import com.kly.dto.SmsRequestDTO;
import com.kly.enums.ProviderEnum;
import com.kly.enums.SendStatusEnum;
import com.kly.msg.db.dao.TMessageDao;
import com.kly.msg.db.entity.TMessageEntity;
import com.kly.msg.strategy.SmsStrategy;
import com.kly.msg.utils.LittleOrangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * @ClassName: ItnitTechStrategy
 * @description: 颂量短信平台对接策略
 * @author: yuwn
 * @create: 2023-11-16 16:43
 */
@Service(value = "itnioTech")
public class ItnioTechStrategy implements SmsStrategy {

    private static Log LOGGER = LogFactory.getLog(ItnioTechStrategy.class);

    @NacosValue(value = "${itnio_tech.api_url:https://api.itniotech.com/sms/sendSms}", autoRefreshed = true)
    private String itnioUrl;

    @NacosValue(value = "${itnio_tech.app_id:tH6uJN7q}", autoRefreshed = true)
    private String appId;

    @NacosValue(value = "${itnio_tech.app_key:tZUWszJFW4dGEGIfVpLECoC0QVA5JVKq}", autoRefreshed = true)
    private String apiKey;

    @NacosValue(value = "${itnio_tech.app_secret:82apyAjHIm4myuai0f7azd88wNnKYl6A}", autoRefreshed = true)
    private String apiSecret;

    @Autowired
    private TMessageDao tMessageDao;

    @NacosValue(value = "${message.template:[Meboo]Your verification code is：}", autoRefreshed = true)
    private String messageTemplate;

    /**
     * 发送短信
     * @param requestDTO
     * @return
     */
    @Transactional
    @Override
    public MsgResultDto sendSms(SmsRequestDTO requestDTO) {

        MsgResultDto msgResultDto = new MsgResultDto();

        // currentTime
        final String datetime = String.valueOf(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond());

        // generate md5 key
        final String sign = MD5.md5(apiKey.concat(apiSecret).concat(datetime));

        Map<String,String> headerMap = new HashMap<>();

        headerMap.put(Headers.CONTENT_TYPE,"application/json;charset=UTF-8");
        headerMap.put(Headers.CONNECTION,"Keep-Alive");
        headerMap.put("Sign",sign);
        headerMap.put("Timestamp",datetime);
        headerMap.put("Api-Key",apiKey);

        Map<String,String> parameterMap = new HashMap<>();
        parameterMap.put("appId",appId);
        parameterMap.put("numbers",requestDTO.getPhone());

        Random random = new Random();
        int verificationCode = 100000 + random.nextInt(900000);
        String content = String.valueOf(verificationCode);
        msgResultDto.setContent(String.valueOf(verificationCode));

        String msg = messageTemplate + content;

        parameterMap.put("content",msg);

        //调用第三方短信时先存储短信请求记录
        TMessageEntity tMessageEntity = new TMessageEntity();
        tMessageEntity.setProviderCode(ProviderEnum.ITNIO_TECH.getCode());
        tMessageEntity.setStatus(SendStatusEnum.INIT.getCode());
        tMessageEntity.setRequestId(UUID.randomUUID().toString());
        tMessageEntity.setTitle(content);
        tMessageEntity.setContent(JSONObject.toJSONString(parameterMap));
        LOGGER.info("颂量请求request:{}，headers:{}",JSONObject.toJSONString(parameterMap),JSONObject.toJSONString(headerMap));
        String response = LittleOrangeService.post(itnioUrl,JSONObject.toJSONString(parameterMap),sign,datetime,apiKey);

//        HttpResponse response = HttpUtils.getUrl(url, headerMap);

        JSONObject result = JSONObject.parseObject(response);
        LOGGER.info("颂量返回结果："+response);
        if("0".equals(result.getString("status"))){

            JSONArray resultArray = result.getJSONArray("array");

            tMessageEntity.setMsgId(resultArray.getJSONObject(0).getString("msgId"));
            tMessageEntity.setFeedbackMsg(response);
        }else{
            tMessageEntity.setStatus(SendStatusEnum.FAILED.getCode());
            tMessageEntity.setFeedbackMsg(response);
        }

        tMessageDao.insert(tMessageEntity);


        msgResultDto.setPhone(requestDTO.getPhone());
        msgResultDto.setContent(content);
        return msgResultDto;
    }

    @Override
    public Boolean smsCallBack(SmsBackRequestDTO smsBackRequestDTO) {

        Map<String, Object> params = Maps.newHashMap();
        params.put("msgId", smsBackRequestDTO.getMsgid());
        params.put("deleted",false);
        params.put("status",SendStatusEnum.INIT.getCode());
        List<TMessageEntity> tMessageEntitys = tMessageDao.selectByParams(params);
        //短信状态初始化的才进行修改
        if(tMessageEntitys.isEmpty()){
            return true;
        }

        TMessageEntity tMessageEntity = tMessageEntitys.get(0);

        if(smsBackRequestDTO.getStatus() == 0){
            tMessageEntity.setStatus(SendStatusEnum.SUCCESS.getCode());
            tMessageEntity.setFeedbackMsg(JSONObject.toJSONString(smsBackRequestDTO));
        }else{
            tMessageEntity.setFeedbackMsg(JSONObject.toJSONString(smsBackRequestDTO));
            tMessageEntity.setStatus(SendStatusEnum.FAILED.getCode());
        }

        tMessageEntity.setGmtModified(new Date());
        tMessageDao.updateByPrimaryKey(tMessageEntity);

        return true;
    }
}
